﻿using System.Html;
using System.Collections.Generic;
using System;

namespace Db7
{
    public static class Queries
    {
        public static VirtualElement GetVirtualElement(Element e)
        {
            Stack<int> TreeNodePath = new Stack<int>();
            Element ancestor = e;
            do
            {
                ElementAttribute ea = ancestor.Attributes.GetNamedItem(VirtualElement._g);
                if (ea == null)
                {
                    if(!RenderContext.ElementLookup.ContainsKey(ancestor.ID)) return null;
                    VirtualElement ve = RenderContext.ElementLookup[ancestor.ID];
                    //Script.Eval("debugger;");
                    if (TreeNodePath.Count > 0) TreeNodePath.Pop();
                    while (TreeNodePath.Count > 0)
                    {
                        int ithElement = TreeNodePath.Pop();
                        ve = ve.Children[ithElement];
                    }
                    return ve;
                }
                TreeNodePath.Push(int.Parse(ea.Value));
                ancestor = ancestor.ParentNode;
            } while (ancestor != null);
            return null;
        }

        public static Element GetElement(VirtualElement ve)
        {
            //Script.Eval("debugger;");
            Stack<int> TreeNodePath = new Stack<int>();
            VirtualElement ancestor = ve;
            while (ancestor.Parent != null)
            {
                TreeNodePath.Push(ancestor.Index);
                ancestor = ancestor.Parent;
            }
            Element containerElement = Document.GetElementById(ancestor.RootContainerId).FirstChild;
            while (TreeNodePath.Count > 0)
            {
                containerElement = containerElement.ChildNodes[TreeNodePath.Pop()];
            }
            return containerElement;
        }
    }
}
